// 使用模力方舟API进行语音合成 - 简洁可靠的流式实现
class VoiceSynthesizer {
    constructor() {
        // 基本配置
        this.base_url = 'https://ai.gitee.com/v1';
        this.API_KEY = 'KQOFBQEBBIZCFT6EJMSCTZCQIKB2R9ZVAQEVWK1P';
        this.isPlaying = false;
        this.debugMode = true;
        
        // 核心音频组件
        this.audioElement = null;
        this.xhr = null;
        this.audioUrl = null;
        this.currentChunk = null;
        this.receivedLength = 0;
    }

    // 日志函数 - 增强调试信息
    log(message) {
        if (this.debugMode) {
            console.log(`[语音合成] ${message}`);
        }
    }

    // 初始化语音合成器
    initSynthesizer() {
        this.log('语音合成器初始化完成');
        return this;
    }

    // 停止播放并清理资源
    stopVoice() {
        // 停止音频播放
        if (this.audioElement) {
            this.audioElement.pause();
            this.audioElement = null;
        }
        
        // 中止请求
        if (this.xhr && this.xhr.readyState !== 4) {
            this.xhr.abort();
            this.xhr = null;
            this.log('请求已中止');
        }
        
        // 释放URL对象
        if (this.audioUrl) {
            try {
                URL.revokeObjectURL(this.audioUrl);
                this.log('URL对象已释放');
            } catch (e) {
                this.log('释放URL对象时出错:', e);
            }
            this.audioUrl = null;
        }
        
        // 重置状态
        this.currentChunk = null;
        this.receivedLength = 0;
        this.isPlaying = false;
        this.log('音频资源已完全清理');
    }

    // 文本预处理
    processText(text) {
        const originalText = text;
        let processedText = text;
        
        // 移除括号内容
        processedText = processedText.replace(/\{[^}]*\}/g, '');
        processedText = processedText.replace(/\[[^\]]*\]/g, '');
        processedText = processedText.replace(/\([^)]*\)/g, '');
        processedText = processedText.replace(/\（[^）]*\）/g, '');
        processedText = processedText.replace(/\s+/g, ' ').trim();

        this.log(`原始文本: ${originalText.substring(0, 50)}${originalText.length > 50 ? '...' : ''}`);
        this.log(`处理后文本: ${processedText.substring(0, 50)}${processedText.length > 50 ? '...' : ''}`);
        
        return processedText;
    }

    // 核心流式合成方法
    async streamVoiceWithStreaming(text) {
        // 停止之前的播放
        this.stopVoice();
        
        try {
            // 创建新的音频元素
            this.audioElement = new Audio();
            this.log('创建新的音频元素');
            
            // 文本预处理
            const processedText = this.processText(text);
            
            // 准备请求参数
            const speechParams = {
                input: processedText,
                model: 'IndexTTS-1.5',
                stream: true,
                prompt_audio_url: 'https://gitee.com/BambooScript-Dialogues/Stream-Cloud-Rhymer/raw/master/%E8%B5%AB%E8%BF%9E%E8%B5%AB%E8%8B%8D.mp3',
            };
            
            this.log('请求参数准备完毕');
            
            // 创建并配置XMLHttpRequest
            this.xhr = new XMLHttpRequest();
            this.xhr.open('POST', `${this.base_url}/audio/speech`, true);
            
            // 设置responseType为arraybuffer
            this.xhr.responseType = 'arraybuffer';
            
            // 设置请求头
            this.xhr.setRequestHeader('Content-Type', 'application/json');
            this.xhr.setRequestHeader('Authorization', `Bearer ${this.API_KEY}`);
            
            // 关键：使用onreadystatechange来处理流式数据
            let isFirstPlay = true;
            
            this.xhr.onreadystatechange = async () => {
                try {
                    // 检查readyState和响应
                    if (this.xhr.readyState > 2 && this.xhr.response) {
                        const currentResponse = this.xhr.response;
                        const currentLength = currentResponse.byteLength;
                        
                        // 只处理新接收到的数据
                        if (currentLength > this.receivedLength) {
                            this.log(`接收到新数据 - 当前长度: ${currentLength}, 新增: ${currentLength - this.receivedLength} 字节`);
                            
                            // 获取完整的响应数据
                            this.currentChunk = currentResponse;
                            this.receivedLength = currentLength;
                            
                            // 创建Blob对象
                            const blob = new Blob([this.currentChunk], { type: 'audio/mpeg' });
                            
                            // 创建新的URL
                            const newAudioUrl = URL.createObjectURL(blob);
                            
                            // 保存当前播放位置
                            let currentTime = 0;
                            if (this.audioElement && !this.audioElement.paused && this.isPlaying) {
                                currentTime = this.audioElement.currentTime;
                                this.log(`保存播放位置: ${currentTime.toFixed(2)}秒`);
                            }
                            
                            // 释放旧URL
                            if (this.audioUrl) {
                                URL.revokeObjectURL(this.audioUrl);
                            }
                            
                            // 设置新URL
                            this.audioUrl = newAudioUrl;
                            this.audioElement.src = this.audioUrl;
                            
                            // 如果是首次播放或有保存的位置，尝试恢复播放
                            if (isFirstPlay) {
                                try {
                                    await this.audioElement.play();
                                    this.isPlaying = true;
                                    isFirstPlay = false;
                                    this.log('音频开始播放');
                                } catch (e) {
                                    this.log('自动播放被阻止:', e.message);
                                }
                            } else if (currentTime > 0) {
                                // 尝试设置到之前的播放位置
                                this.audioElement.currentTime = currentTime;
                                this.log(`尝试恢复到之前的播放位置: ${currentTime.toFixed(2)}秒`);
                            }
                        }
                    }
                    
                    // 请求完成
                    if (this.xhr.readyState === 4) {
                        this.log(`请求完成 - 状态码: ${this.xhr.status}`);
                        
                        if (this.xhr.status === 200) {
                            // 最终播放尝试
                            if (!this.isPlaying) {
                                try {
                                    await this.audioElement.play();
                                    this.isPlaying = true;
                                    this.log('音频最终播放成功');
                                } catch (e) {
                                    this.log('最终播放失败:', e.message);
                                    throw new Error('无法播放音频，请检查浏览器设置');
                                }
                            }
                        } else {
                            const errorMessage = `API请求失败: ${this.xhr.status} ${this.xhr.statusText}`;
                            this.log(errorMessage);
                            this.stopVoice();
                            throw new Error(errorMessage);
                        }
                    }
                } catch (error) {
                    this.log('处理流式数据时出错:', error.message);
                }
            };
            
            // 监听音频事件
            this.audioElement.addEventListener('error', (e) => {
                this.log('音频元素错误:', e);
                this.stopVoice();
            });
            
            this.audioElement.addEventListener('ended', () => {
                this.isPlaying = false;
                this.log('音频播放结束');
            });
            
            // 监听网络错误
            this.xhr.onerror = () => {
                this.log('网络请求错误');
                this.stopVoice();
                throw new Error('网络请求失败');
            };
            
            this.xhr.onabort = () => {
                this.log('请求已中止');
            };
            
            // 发送请求
            this.log('开始发送请求...');
            this.xhr.send(JSON.stringify(speechParams));
            
            // 返回控制对象
            return {
                stop: () => this.stopVoice(),
                isPlaying: () => this.isPlaying && this.audioElement && !this.audioElement.paused
            };
            
        } catch (error) {
            console.error('语音生成失败:', error);
            this.stopVoice();
            throw error;
        }
    }

    // 为聊天消息添加语音按钮
    addVoiceButtons() {
        // 监听新消息添加
        const observer = new MutationObserver(mutations => {
            mutations.forEach(mutation => {
                if (mutation.type === 'childList') {
                    mutation.addedNodes.forEach(node => {
                        if (node.classList && node.classList.contains('message') &&
                            node.classList.contains('received')) {
                            // 检查是否已经添加了语音按钮
                            if (!node.querySelector('.voice-button')) {
                                this.addVoiceButtonToMessage(node);
                            }
                        }
                    });
                }
            });
        });

        // 开始观察聊天消息容器
        const chatMessages = document.getElementById('chat-messages');
        if (chatMessages) {
            observer.observe(chatMessages, {
                childList: true,
                subtree: true
            });
            this.log('开始监听消息添加事件');
        } else {
            this.log('未找到聊天消息容器');
        }
    }

    // 显示错误消息
    showErrorMessage(title, message) {
        // 检查是否已经存在错误弹窗
        let errorModal = document.getElementById('voice-error-modal');
        if (errorModal) {
            document.body.removeChild(errorModal);
        }

        // 创建错误弹窗容器
        errorModal = document.createElement('div');
        errorModal.id = 'voice-error-modal';
        errorModal.style.position = 'fixed';
        errorModal.style.top = '50%';
        errorModal.style.left = '50%';
        errorModal.style.transform = 'translate(-50%, -50%)';
        errorModal.style.backgroundColor = '#333';
        errorModal.style.color = 'white';
        errorModal.style.padding = '20px';
        errorModal.style.borderRadius = '8px';
        errorModal.style.boxShadow = '0 4px 20px rgba(0, 0, 0, 0.5)';
        errorModal.style.zIndex = '10000';
        errorModal.style.maxWidth = '400px';
        errorModal.style.width = '90%';
        errorModal.style.textAlign = 'center';
        errorModal.style.fontFamily = 'Arial, sans-serif';

        // 创建标题
        const titleElement = document.createElement('h3');
        titleElement.textContent = title;
        titleElement.style.marginTop = '0';
        titleElement.style.color = '#f0f0f0';
        errorModal.appendChild(titleElement);

        // 创建消息内容
        const messageElement = document.createElement('p');
        messageElement.textContent = message;
        messageElement.style.margin = '15px 0';
        messageElement.style.lineHeight = '1.5';
        errorModal.appendChild(messageElement);

        // 创建关闭按钮
        const closeButton = document.createElement('button');
        closeButton.textContent = '关闭';
        closeButton.style.padding = '8px 16px';
        closeButton.style.backgroundColor = '#555';
        closeButton.style.color = 'white';
        closeButton.style.border = 'none';
        closeButton.style.borderRadius = '4px';
        closeButton.style.cursor = 'pointer';
        closeButton.style.fontSize = '14px';

        // 添加关闭事件
        closeButton.addEventListener('click', () => {
            document.body.removeChild(errorModal);
        });

        errorModal.appendChild(closeButton);

        // 添加到文档
        document.body.appendChild(errorModal);
    }

    // 为单个消息添加语音按钮
    addVoiceButtonToMessage(messageElement) {
        const contentElement = messageElement.querySelector('.message-content');
        if (!contentElement) return;
    
        const textElement = contentElement.querySelector('p');
        if (!textElement) return;
    
        // 创建语音按钮
        const voiceButton = document.createElement('button');
        voiceButton.className = 'voice-button';
        voiceButton.title = '播放语音';
        voiceButton.innerHTML = '🔊';
    
        // 添加点击事件
        voiceButton.addEventListener('click', async () => {
            try {
                // 获取消息文本
                const text = textElement.textContent || textElement.innerText;
    
                // 切换按钮状态
                if (voiceButton.getAttribute('data-playing') === 'true') {
                    // 停止播放
                    this.stopVoice();
                    voiceButton.setAttribute('data-playing', 'false');
                    voiceButton.innerHTML = '🔊';
                } else {
                    // 开始播放
                    voiceButton.setAttribute('data-playing', 'true');
                    voiceButton.innerHTML = '⏸️';
    
                    // 生成并播放语音
                    const voiceControl = await this.streamVoiceWithStreaming(text);
    
                    // 监听播放状态变化
                    const checkStatus = setInterval(() => {
                        if (!voiceControl.isPlaying()) {
                            voiceButton.setAttribute('data-playing', 'false');
                            voiceButton.innerHTML = '🔊';
                            clearInterval(checkStatus);
                        }
                    }, 500);
                }
            } catch (error) {
                console.error('语音播放失败:', error);
                // 使用自定义错误弹窗
                this.showErrorMessage('语音播放失败', error.message);
                voiceButton.setAttribute('data-playing', 'false');
                voiceButton.innerHTML = '🔊';
            }
        });
    
        // 将按钮添加到消息的左上角（修改这部分）
        contentElement.style.position = 'relative';
        contentElement.insertBefore(voiceButton, contentElement.firstChild);
    }
}

// 当页面加载完成后初始化语音合成器
window.addEventListener('load', () => {
    // 等待主script.js加载完成
    setTimeout(() => {
        try {
            const voiceSynthesizer = new VoiceSynthesizer();
            voiceSynthesizer.initSynthesizer();
            // 将语音合成器暴露给全局
            window.voiceSynthesizer = voiceSynthesizer;

            // 添加语音按钮到现有和新的消息
            voiceSynthesizer.addVoiceButtons();

            console.log('语音合成器初始化完成');
        } catch (error) {
            console.error('语音合成器初始化失败:', error);
        }
    }, 500); // 减少等待时间，让语音按钮更快出现
});